<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="80px">
      <el-row>
        <!-- <el-col :span="8"> -->
          <el-form-item label="人群名称" prop="groupName">
            <el-input v-model="queryParams.groupName" placeholder="请输入人群名称" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        <!-- </el-col>
        <el-col :span="8"> -->
          <el-form-item
            style="margin-left: 20px;">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        <!-- </el-col> -->
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['group:CustomerGroup:add']">新建人群</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="CustomerGroupList" @selection-change="handleSelectionChange">
        <el-table-column label="人群名称" align="center" prop="groupName" :show-overflow-tooltip="true" />
        <el-table-column label="人群定义" align="center" prop="groupDefinition" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span style="
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            " :title="item.groupDefinition" v-for="(item, index) in scope.row.customerGroupdefinitionInfoVos "
              :key="index">
              <span v-if="item.customerGroupDefinitionVo!=null">
                <span
                  v-if="item.customerGroupDefinitionVo.definitionName === 'sex' && item.definitionValue != null && item.customerGroupDefinitionVo.definitionName != null ">
                  {{ item.customerGroupDefinitionVo.definitionShowname }}
                  <span v-if="item.definitionValue == '1' ">男</span>
                  <span v-if="item.definitionValue == '2' ">女</span>
                  &nbsp;
                </span>
                <span v-else>
                  {{ item.customerGroupDefinitionVo.definitionShowname }}
                  <span v-if="item.definitionUnitvalue != null && item.definitionUnitvalue == 'ge' ">大于</span>
                  <span v-if="item.definitionUnitvalue != null && item.definitionUnitvalue == 'le' ">小于</span>
                  <span
                    v-if="item.definitionUnitvalue != null && item.definitionUnitvalue == 'section' ">{{item.definitionValue}}到{{item.definitionSectionvalue}}之间</span>
                  <span v-else>{{item.definitionValue}}</span>
                  &nbsp;
                </span>
              </span>

            </span>
          </template>
        </el-table-column>
        <el-table-column label="人群描述" min-width="120" align="center" prop="groupDesc" :show-overflow-tooltip="true" />
        <el-table-column label="人群数量" align="center" prop="groupNumber" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.groupNumber != null">
              {{ scope.row.groupNumber }}
            </span>
            <span v-if="scope.row.groupNumber == null">
              0
            </span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleShowCustoemr(scope.row)"
              v-hasPermi="['group:CustomerGroup:query']">查看客户</el-button>

            <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="goOperation(scope.row)"
              v-hasPermi="['group:CustomerGroup:query']">去运营</el-button>

            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['group:CustomerGroup:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['group:CustomerGroup:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改客户分群对话框 -->
    <updateGroup v-if="Openupdate" :updateGroupStr.sync="Openupdate" :updateGroup="updateDate" @getData="getList">
    </updateGroup>

    <!-- 条件查看客户信息 -->
    <el-dialog :title="queryTitle" :visible.sync="queryOpen" width="900px" append-to-body>
      <el-table v-loading="queryLoading" :data="queryCustomerInfo">
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="头像" align="center" prop="headImage">
          <template slot-scope="scope">
            <el-image style="border-radius:50px;" v-if="scope.row.headImage != null && scope.row.headImage != '' "
              slot="reference" :src="scope.row.headImage" class="image-rows" :preview-src-list="[scope.row.headImage]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contactMan" />
        <el-table-column label="手机号码" align="center" prop="phone">
          <template slot-scope="scope">
            <span style="color: #00AAFF;" @click="showPhone(scope.row)">
              {{scope.row.phoneStr}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="sex" :formatter="sexFormat" />
        <el-table-column label="省份" align="center" prop="province" />
        <el-table-column label="详细地址" align="center" prop="addressDetail" />
        <el-table-column label="总积分" align="center" prop="allScore" />
      </el-table>
      <pagination v-show="queryTotal>0" :total="queryTotal" :page.sync="queryCustomerInfoParams.pageNum" :limit.sync="queryCustomerInfoParams.pageSize"
        @pagination="showCustomerInfo" />
    </el-dialog>

    <!-- 查看客户分群对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>
      <el-form ref="detailForm" label-width="100px">
        <el-row>
          <el-col :span="12" v-for="(item, index) in showData" :key="index" style="margin-top:-15px">
            <el-form-item :label="`${item.label}：`">
              <span>{{item.value}}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handCloseDetail">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listCustomerGroup,
    getCustomerGroup,
    delCustomerGroup,
    addCustomerGroup,
    updateCustomerGroup,
    selectGroupCustomerInfo
  } from "@/api/customer/CustomerGroup";
  import {
    getCustomerInfoByids
  } from "@/api/customer/Info";
  import updateGroup from "@/components/Customer/updateGroup";

  export default {
    name: "CustomerGroup",
    components: {
      updateGroup
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        //条件查询客户遮罩层
        queryLoading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 客户分群表格数据
        CustomerGroupList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //查看详细数据
        showData: [],
        //修改数据
        updateDate: [],
        // 性别 1男，0女字典
        sexOptions: [],
        //条件查询客户数组
        groupDefinitionInfoQuerie: [],
        //条件查询客户信息
        queryCustomerInfo: [],
        // 条件查询客户信息总条数
        queryTotal: 0,
        //查询客户open
        queryOpen: false,
        //查询客户title
        queryTitle: "",
        //添加修改组件:
        Openupdate: false,
        //客户id数组
        customerUidArr:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          groupName: null,
        },
        // 条件查询参数
        queryCustomerInfoParams: {
          pageNum: 1,
          pageSize: 10,
          groupName: null,
        },
        columns: [{
            label: '客户分群ID',
            dataIndex: 'groupUid',
          },
          {
            label: '平台ID',
            dataIndex: 'platformId',
          },
          {
            label: '分群名称',
            dataIndex: 'groupName',
          },
          {
            label: '分群定义',
            dataIndex: 'groupDefinition',
          },
          {
            label: '分群数量',
            dataIndex: 'groupNumber',
          },
          {
            label: '创建时间',
            dataIndex: 'createTime',
          },
          {
            label: '修改时间',
            dataIndex: 'updateTime',
          },
          {
            label: '创建人',
            dataIndex: 'createUser',
          },
          {
            label: '修改人',
            dataIndex: 'updateUser',
          },
          {
            label: '状态，1有限，0无效，-1删除',
            dataIndex: 'dataStatus',
          },
          {
            label: '创建人名称',
            dataIndex: 'createName',
          },
          {
            label: '修改人名称',
            dataIndex: 'updateName',
          },
        ],
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      };
    },
    created() {
      this.getDicts("customer_sex").then(response => {
        this.sexOptions = response.data;
      });
      this.getList();
    },
    methods: {
      // 性别 1男，0女字典翻译
      sexFormat(row, column) {
        return this.selectDictLabel(this.sexOptions, row.sex);
      },
      /** 查询客户分群列表 */
      getList() {
        this.loading = true;
        listCustomerGroup(this.queryParams).then(response => {
          this.CustomerGroupList = response.rows;
          console.log(this.CustomerGroupList);
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          groupUid: null,
          platformId: null,
          groupName: null,
          groupDefinition: null,
          groupNumber: null,
          createTime: null,
          updateTime: null,
          createUser: null,
          updateUser: null,
          dataStatus: "0",
          createName: null,
          updateName: null
        };
        this.resetForm("form");
      },
      //显示隐藏手机号
      showPhone(row) {
        row.PhoneUpdate = row.phone;
        if (row.phoneStr.indexOf("*") != -1 == false) {
          row.PhoneUpdate = row.phoneStr;
          var len = row.phone.length - 3 - 4;
          var xing = '';
          for (var i = 0; i < len; i++) {
            xing += "*";
          }
          row.phoneStr = row.phone.substring(0, 3) + xing + row.phone.substring(row.phone.length - 4)
        } else {
          row.phoneStr = row.PhoneUpdate;
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.groupUid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.updateDate = [];
        this.Openupdate = true;
        // this.open = true;
        this.title = "添加客户分群";
        this.getList();
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        this.viewOpen = true;
        this.viewTitle = "查看客户分群";
        this.showData = [];
        this.columns.forEach(item => {
          this.showData.push({
            label: item.label,
            value: row[item.dataIndex]
          })
        })
      },
      handCloseDetail() {
        this.viewOpen = false
        this.showData = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.updateDate = [];
        const groupUid = row.groupUid || this.ids
        getCustomerGroup(groupUid).then(response => {
          this.Openupdate = true;
          this.updateDate = response.data;
          this.form = response.data;
          this.open = true;
          this.title = "修改客户分群";
          this.getList();
        });
      },
      /** 提交按钮 */
      submitForm() {
        console.log(123)
        // this.$refs["form"].validate(valid => {
        //   if (valid) {
        //     console.log(valid);
        //     // if (this.form.groupUid != null) {
        //     //   updateCustomerGroup(this.form).then(response => {
        //     //     this.msgSuccess("修改成功");
        //     //     this.open = false;
        //     //     this.getList();
        //     //   });
        //     // } else {
        //     //   addCustomerGroup(this.form).then(response => {
        //     //     this.msgSuccess("新增成功");
        //     //     this.open = false;
        //     //     this.getList();
        //     //   });
        //     // }
        //   }
        // });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const groupUids = row.groupUid || this.ids;
        this.$confirm('是否确认删除客户分群名称为"' + row.groupName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCustomerGroup(groupUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('customer/CustomerGroup/export', {
          ...this.queryParams
        }, `group_CustomerGroup.xlsx`)
      },
      //查看客户
      handleShowCustoemr(row) {
        let than = this;
        this.DefinitionQuerie = {};
        this.groupDefinitionInfoQuerie = [];
        console.log(row.customerGroupdefinitionInfoVos);
        row.customerGroupdefinitionInfoVos.forEach(item => {
          let DefinitionQuerie = new Object();
          DefinitionQuerie.definitionUid = item.definitionUid;
          if(item.definitionValue != null){
            if(item.definitionValue.indexOf("/") != -1){
              let definitionValue = "";
              let splitVal =  item.definitionValue.split("/");
              for (var i = 0; i < splitVal.length; i++) {
                if(splitVal[i] != ""){
                  definitionValue+=splitVal[i];
                }
              }
              DefinitionQuerie.definitionValue = definitionValue;
            }else{
              DefinitionQuerie.definitionValue = item.definitionValue;
            }
          }

          if(item.definitionSectionvalue != null){
            if(item.definitionSectionvalue.indexOf("/") != -1){
              let definitionSectionvalue = "";
              let splitVal =  item.definitionSectionvalue.split("/");
              for (var i = 0; i < splitVal.length; i++) {
                if(splitVal[i] != ""){
                  definitionSectionvalue+=splitVal[i];
                }
              }
              DefinitionQuerie.definitionSectionvalue = definitionSectionvalue;
            }else{

            }
          DefinitionQuerie.definitionSectionvalue = item.definitionSectionvalue;
          }
          DefinitionQuerie.definitionUnitvalue = item.definitionUnitvalue;
          this.groupDefinitionInfoQuerie.push(DefinitionQuerie);
        })
        console.log(this.groupDefinitionInfoQuerie);
        selectGroupCustomerInfo(this.groupDefinitionInfoQuerie).then((response) => {
          let customerUid = response;
          if(customerUid.length > 0){
            this.customerUidArr = [];
            this.customerUidArr = response;
            this.queryLoading = true;
            getCustomerInfoByids(this.queryCustomerInfoParams,customerUid).then((response) => {
              this.queryCustomerInfo = response.rows;
              this.queryTotal = response.total;
              this.queryOpen = true;
              this.queryTitle = "查看客户信息";
              this.queryLoading = false;
            })
          }else{
            this.msgError("当前人群特征没有客户信息");
          }
        });
      },
      showCustomerInfo(){
        let customerUid = this.customerUidArr;
        getCustomerInfoByids(this.queryCustomerInfoParams,customerUid).then((response) => {
          this.queryCustomerInfo = response.rows;
          this.queryTotal = response.total;
          this.queryOpen = true;
          this.queryTitle = "查看客户信息";
          this.queryLoading = false;
        })
      },
      //跳转运营
      goOperation(row) {
        this.$router.push("/updateOperation/updateOperation/"+ row.groupUid);
      }


    }
  };
</script>
